<template>
<ion-page :className="{ 'view-container': true, 'default-mode-view': true, 'demobwfdynaexpmdview': true, 'shop-examine-mob-wfdyna-exp-mdview': true, 'mdview-white-filter': true }">
    
    <app-mob-header>
        <ion-toolbar v-show="titleStatus" class="ionoc-view-header">
            <ion-buttons slot="start">
                <app-mob-button 
                    v-show="isShowBackButton" 
                    ref="backbtn"
                    iconName="chevron-back" 
                    :text="$t('app.button.back')" 
                    @click="closeView" />
            </ion-buttons>
            <app-mob-title class="view-title"><label class="title-label"><app-mob-icon v-if="model.icon" :name="model.icon"></app-mob-icon> <img v-else-if="model.iconcls" :src="model.iconcls" alt=""> {{$t(model.srfCaption)}}</label></app-mob-title>
        </ion-toolbar>
        <app-search-history @quickValueChange="quickValueChange" :model="model" :showfilter="false"></app-search-history>

    
                    <ion-toolbar>
                <ion-segment :scrollable="true" value="0">
                    <ion-segment-button v-for="(item,index) in wfStepModel" :key="index" @click="tab_click(item)" :value="index">
                        <ion-label>{{item.userTaskName}}</ion-label>
                    </ion-segment-button>
                </ion-segment>
            </ion-toolbar>
    </app-mob-header>

    <ion-content :scroll-events="true" @ionScroll="onScroll" ref="ionScroll" @ionScrollEnd="onScrollEnd">
        <ion-refresher 
            slot="fixed" 
            ref="loadmore" 
            pull-factor="0.5" 
            pull-min="50" 
            pull-max="100" 
            @ionRefresh="pullDownToRefresh($event)">
            <ion-refresher-content
                pulling-icon="arrow-down-outline"
                :pulling-text="$t('app.pulling_text')"
                refreshing-spinner="circles"
                refreshing-text="">
            </ion-refresher-content>
        </ion-refresher>
                <view_mdctrl
            :viewState="viewState"
            viewName="MobWFDynaExpMDView"
            :viewparams="viewparams" 
            :context="context" 
            viewType="DEMOBWFDYNAEXPMDVIEW"
            controlStyle="LISTVIEW"
            updateAction="Update"
            removeAction="Remove"
            loaddraftAction=""
            loadAction="Get"
            createAction="Create"
            fetchAction="FetchDefault" 
            :isMutli="!isSingleSelect"
            :isNeedLoaddingText="!isPortalView"
            :showBusyIndicator="true" 
            :isTempMode="false"
            name="mdctrl"  
            ref='mdctrl' 
            @closeview="closeView($event)">
        </view_mdctrl>
    </ion-content>
    <ion-footer class="view-footer">
        
    </ion-footer>
</ion-page>
</template>

<script lang='ts'>
import { Vue, Component, Prop, Provide, Emit, Watch } from 'vue-property-decorator';
import { Subject, Subscription } from 'rxjs';
import GlobalUiService from '@/global-ui-service/global-ui-service';
import Shop_examineService from '@/app-core/service/shop-examine/shop-examine-service';

import Shop_examineUIService from '@/ui-service/shop-examine/shop-examine-ui-action';
import { AnimationService } from '@ibiz-core/service/animation-service'

@Component({
    components: {
    },
})
export default class Shop_examineMobWFDynaExpMDViewBase extends Vue {

    /**
     * 全局ui服务
     *
     * @type {GlobalUiService}
     * @memberof Shop_examineMobWFDynaExpMDViewBase
     */
    protected globaluiservice: GlobalUiService = new GlobalUiService();

    /**
     * 实体服务对象
     *
     * @type {Shop_examineService}
     * @memberof Shop_examineMobWFDynaExpMDViewBase
     */
    protected appEntityService: Shop_examineService = new Shop_examineService();

    /**
     * 实体UI服务对象
     *
     * @type Shop_examineUIService
     * @memberof Shop_examineMobWFDynaExpMDViewBase
     */
    public appUIService: Shop_examineUIService = new Shop_examineUIService(this.$store);

    /**
     * 数据变化
     *
     * @param {*} val
     * @returns {*}
     * @memberof Shop_examineMobWFDynaExpMDViewBase
     */
    @Emit() 
    protected viewDatasChange(val: any):any {
        return val;
    }

    /**
     * 视图上下文
     *
     * @type {string}
     * @memberof Shop_examineMobWFDynaExpMDViewBase
     */
    @Prop() protected _context!: string;

    /**
     * 视图参数
     *
     * @type {string}
     * @memberof Shop_examineMobWFDynaExpMDViewBase
     */
    @Prop() protected _viewparams!: string;

    /**
     * 视图默认使用
     *
     * @type {boolean}
     * @memberof Shop_examineMobWFDynaExpMDViewBase
     */
    @Prop({ default: "routerView" }) protected viewDefaultUsage!: string;

	/**
	 * 视图标识
	 *
	 * @type {string}
	 * @memberof Shop_examineMobWFDynaExpMDViewBase
	 */
	protected viewtag: string = 'c0ab4505ff0a23e9f530646ede61cfb2';

    /**
     * 视图上下文
     *
     * @type {*}
     * @memberof Shop_examineMobWFDynaExpMDViewBase
     */
    protected context: any = {};

    /**
     * 视图参数
     *
     * @type {*}
     * @memberof Shop_examineMobWFDynaExpMDViewBase
     */
    protected viewparams: any = {};

    /**
     * 是否为子视图
     *
     * @type {boolean}
     * @memberof Shop_examineMobWFDynaExpMDViewBase
     */
    @Prop({ default: false }) protected isChildView?: boolean;

    /**
     * 是否为门户嵌入视图
     *
     * @type {boolean}
     * @memberof Shop_examineMobWFDynaExpMDViewBase
     */
    @Prop({ default: false }) protected isPortalView?: boolean;

    /**
     * 标题状态
     *
     * @memberof Shop_examineMobWFDynaExpMDViewBase
     */
    public titleStatus :boolean = true;

    /**
     * 视图导航上下文
     *
     * @protected
     * @type {*}
     * @memberof Shop_examineMobWFDynaExpMDViewBase
     */
    protected navContext: any = {};

    /**
     * 视图导航参数
     *
     * @protected
     * @type {*}
     * @memberof Shop_examineMobWFDynaExpMDViewBase
     */
    protected navParam: any = { 'srfwf': 'todo' };

    /**
     * 视图模型数据
     *
     * @type {*}
     * @memberof Shop_examineMobWFDynaExpMDViewBase
     */
    protected model: any = {
        srfTitle: '入驻审核',
        srfCaption: 'shop_examine.views.mobwfdynaexpmdview.caption',
        srfSubCaption: '',
        dataInfo: '',
        viewname:'shop_examine.mobwfdynaexpmdview',
        iconcls: '',
        icon: ''
    }

    /**
     * 视图上下文变化
     *
     * @param {string} newVal
     * @param {string} oldVal
     * @memberof  Shop_examineMobWFDynaExpMDViewBase
     */
    @Watch('_context')
    on_context(newVal: string, oldVal: string) {
        const _this: any = this;
        this.parseViewParam();
        if (!Object.is(newVal, oldVal) && _this.engine) {
            this.$nextTick(()=>{_this.engine.load();})
        }
        
    }

    /**
     * 视图参数变化
     *
     * @param {string} newVal
     * @param {string} oldVal
     * @returns
     * @memberof IBizChart
     */
    @Watch('_viewparams',{immediate: true, deep: true})
    on_viewparams(newVal: string, oldVal: string) {
        this.parseViewParam();
        
    }

    /**
     * 设置工具栏状态
     *
     * @memberof Shop_examineMobWFDynaExpMDViewBase
     */
    public setViewTitleStatus(){
        const thirdPartyName = this.$store.getters.getThirdPartyName();
        if(thirdPartyName){
            this.titleStatus = false;
        }
    }

    /**
     * 容器模型
     *
     * @type {*}
     * @memberof Shop_examineMobWFDynaExpMDViewBase
     */
    protected containerModel: any = {
        view_mdctrl: { name: 'mdctrl', type: 'MOBMDCTRL' },
        wflinks: [],
    };

    /**
     * 视图状态订阅对象
     *
     * @type {Subject<{action: string, data: any}>}
     * @memberof Shop_examineMobWFDynaExpMDViewBase
     */
    protected viewState: Subject<ViewState> = new Subject();


    /**
     * 是否显示标题
     *
     * @type {string}
     * @memberof Shop_examineMobWFDynaExpMDViewBase
     */
    @Prop({default:true}) protected showTitle?: boolean;


    /**
     * 工具栏模型集合名
     *
     * @memberof Shop_examineMobWFDynaExpMDViewBase
     */
    public toolbarModelList:any = []

    /**
     * 解析视图参数
     *
     * @memberof Shop_examineMobWFDynaExpMDViewBase
     */
    protected parseViewParam(): void {
        const { context, param } = this.$viewTool.formatNavigateViewParam(this, true);
        this.context = { ...context };
        this.viewparams = { ...param }
    }

    /**
     * 是否显示返回按钮
     *
     * @readonly
     * @type {boolean}
     * @memberof Shop_examineMobWFDynaExpMDViewBase
     */
    get isShowBackButton(): boolean {
        // 存在路由，非路由使用，嵌入
        if (this.viewDefaultUsage === "indexView") {
            return false;
        }
        return true;
    }

    /**
     * 下拉刷新
     *
     * @param {*} $event
     * @returns {Promise<any>}
     * @memberof Shop_examineMobWFDynaExpMDViewBase
     */
    public async pullDownToRefresh($event: any): Promise<any> {
        setTimeout(() => {
            $event.srcElement.complete();
        }, 2000);
    }


    /**
     * 引擎初始化
     *
     * @memberof Shop_examineMobWFDynaExpMDViewBase
     */
    protected engineInit(): void {
    }

    /**
     * Vue声明周期
     *
     * @memberof Shop_examineMobWFDynaExpMDViewBase
     */
    protected created() {
        this.afterCreated();
    }

    /**
     * 执行created后的逻辑
     *
     * @memberof Shop_examineMobWFDynaExpMDViewBase
     */    
    protected afterCreated(){
        const secondtag = this.$util.createUUID();
        this.$store.commit('viewaction/createdView', { viewtag: this.viewtag, secondtag: secondtag });
        this.viewtag = secondtag;
        this.parseViewParam();
        this.setViewTitleStatus();


    }


    /**
     * 销毁之前
     *
     * @memberof Shop_examineMobWFDynaExpMDViewBase
     */
    protected beforeDestroy() {
        this.$store.commit('viewaction/removeView', this.viewtag);
    }

    /**
     * Vue声明周期
     *
     * @memberof Shop_examineMobWFDynaExpMDViewBase
     */
    public activated() {
        this.thirdPartyInit();
    }



    /**
     * Vue声明周期(组件初始化完毕)
     *
     * @memberof Shop_examineMobWFDynaExpMDViewBase
     */
    protected mounted() {
        this.afterMounted();
    }


    /**
     * 执行mounted后的逻辑
     * 
     * @memberof Shop_examineMobWFDynaExpMDViewBase
     */
    protected afterMounted(){
        const _this: any = this;
        _this.engineInit();
        if (_this.loadModel && _this.loadModel instanceof Function) {
            _this.loadModel();
        }
        this.thirdPartyInit();

    }

    /**
     * 第三方容器初始化
     * 
     * @memberof Shop_examineMobWFDynaExpMDViewBase
     */
    protected  thirdPartyInit(){
        const _this:any = this;  
        if(!this.isChildView){
            this.$viewTool.setViewTitleOfThirdParty(this.$t(this.model.srfCaption) as string);
            this.$viewTool.setThirdPartyEvent(this.closeView);
            this.$viewTool.initRightBtn(_this.righttoolbarModels,_this.righttoolbar_click);
        }
    }

    /**
     * 销毁视图回调
     *
     * @memberof Shop_examineMobWFDynaExpMDViewBase
     */
    protected destroyed(){
        this.afterDestroyed();
    }

    /**
     * 执行destroyed后的逻辑
     * 
     * @memberof Shop_examineMobWFDynaExpMDViewBase
     */
    protected afterDestroyed(){
        if (this.viewDefaultUsage !== "indexView" && Object.keys(localStorage).length > 0) {
            Object.keys(localStorage).forEach((item: string) => {
                if (item.startsWith(this.context.srfsessionid)) {
                    localStorage.removeItem(item);
                }
            });
        }

    }


    /**
     * 打开编辑数据视图
     *
     * @param {any[]} args
     * @param {*} [contextJO={}]
     * @param {*} [paramJO={}]
     * @param {*} [$event]
     * @param {*} [xData]
     * @param {*} [container]
     * @param {string} [srfParentDeName]
     * @returns {Promise<any>}
     * @memberof Shop_examineMobWFDynaExpMDView
     */
    public async opendata(args: any[], contextJO: any = {}, paramJO: any = {}, $event?: any, xData?: any, container?: any, srfParentDeName?: string): Promise<any> {
        const params: any = { ...paramJO };
        let _context = { ...this.context, ...contextJO };
        if (args.length > 0) {
            Object.assign(_context, args[0]);
        }
        let response: any = null;
        let panelNavParam = { } ;
        let panelNavContext = { } ;
        //导航参数处理
        const { context, param: _params } = this.$viewTool.formatNavigateParam( panelNavContext, panelNavParam, _context, params, {});
        const deResParameters: any[] = [];
        const parameters: any[] = [
            { pathName: 'shop_examines', parameterName: 'shop_examine' },
            { pathName: 'mobwfdynaeditview', parameterName: 'mobwfdynaeditview' },
        ];
        if (args[0]['srfprocessdefinitionkey'] && args[0]['srftaskdefinitionkey']) {
            Object.assign(_params, {
                processDefinitionKey: args[0]['srfprocessdefinitionkey'],
                taskDefinitionKey: args[0]['srftaskdefinitionkey']
            });
            const _this: any = this;
            if (args[0]['srftaskid']) {
                Object.assign(_params, { srftaskid: args[0]['srftaskid'] });
            }
            if (_this.quickGroupData && _this.quickGroupData.hasOwnProperty('srfwf')) {
                Object.assign(_params, { srfwf: _this.quickGroupData.hasOwnProperty('srfwf') });
            }
        }
        const routeParam: any = this.globaluiservice.openService.formatRouteParam(context, deResParameters, parameters, args, _params);
        response = await this.globaluiservice.openService.openView(routeParam);
        if (response) {
            if (!response || !Object.is(response.ret, 'OK')) {
                return;
            }
            if (!xData || !(xData.refresh instanceof Function)) {
                return;
            }
            xData.refresh(response.datas);
        }
    }


    /**
     * 第三方关闭视图
     *
     * @param {any[]} args
     * @memberof Shop_examineMobWFDynaExpMDViewBase
     */
    public quitFun() {
        if (!sessionStorage.getItem("firstQuit")) {  // 首次返回时
            // 缓存首次返回的时间
            window.sessionStorage.setItem("firstQuit", new Date().getTime().toString());
            // 提示再按一次退出
            this.$toast("再按一次退出");
            // 两秒后清除缓存（与提示的持续时间一致）
            setTimeout(() => {window.sessionStorage.removeItem("firstQuit")}, 2000);
        } else {
            // 获取首次返回时间
            let firstQuitTime: any = sessionStorage.getItem("firstQuit");
            // 如果时间差小于两秒 直接关闭
            if (new Date().getTime() - firstQuitTime < 2000) {
                this.$viewTool.ThirdPartyClose();
            }
        }
    }
    
    /**
     * 关闭视图
     *
     * @param {any[]} args
     * @memberof Shop_examineMobWFDynaExpMDViewBase
     */
    protected async closeView(args: any[]): Promise<any> {
        if(this.$store.state.searchformStatus){
             this.$store.commit('setSearchformStatus',false);
             return
        }
        if(this.viewDefaultUsage==="indexView" && this.$route.path === '/appindexview'){
            this.quitFun();
            return;
        }
        if (this.viewDefaultUsage === "routerView" ) {
           if(window.history.length == 1 && this.$viewTool.getThirdPartyName()){
                this.quitFun();
            }else{
                this.$store.commit("deletePage", this.$route.fullPath);
                this.$router.go(-1);
           }
        }
        if (this.viewDefaultUsage === "actionView") {
            this.$emit("close", { status: "success", action: "close", data: args instanceof MouseEvent ? null : args });
        }
        
    }

    /**
     * 刷新数据
     *
     * @readonly
     * @type {(number | null)}
     * @memberof Shop_examineMobWFDynaExpMDViewBase
     */
    get refreshdata(): number | null {
        return this.$store.getters['viewaction/getRefreshData'](this.viewtag);
    }

    /**
     * 监控数据变化
     *
     * @param {*} newVal
     * @param {*} oldVal
     * @returns
     * @memberof Shop_examineMobWFDynaExpMDViewBase
     */
    @Watch('refreshdata')
    onRefreshData(newVal: any, oldVal: any) {
        if (newVal === null || newVal === undefined) {
            return;
        }
        if (newVal === 0) {
            return;
        }
        const _this: any = this;
        if (_this.onRefreshView && _this.onRefreshView instanceof Function) {
            _this.onRefreshView();
        }
    }

    /**
     * 初始化导航栏标题
     *
     * @param {*} val
     * @param {boolean} isCreate
     * @returns
     * @memberof Shop_examineMobWFDynaExpMDViewBase
     */
    public initNavCaption(val:any,isCreate:boolean){
        this.$viewTool.setViewTitleOfThirdParty(this.$t(this.model.srfCaption) as string);        
    }

    /**
     * onScroll滚动事件
     *
     * @memberof Shop_examineMobWFDynaExpMDViewBase
     */
    public async onScroll(e:any){
        this.isScrollStop = false;
        if (e.detail.scrollTop>600) {
            this.isShouleBackTop = true;
        }else{
            this.isShouleBackTop = false;
        }
    }

    /**
     * onScroll滚动结束事件
     *
     * @memberof Shop_examineMobWFDynaExpMDViewBase
     */
    public onScrollEnd(){
        this.isScrollStop = true;
    }

    /**
     * 返回顶部
     *
     * @memberof Shop_examineMobWFDynaExpMDViewBase
     */
    public onScrollToTop() {
        let ionScroll:any = this.$refs.ionScroll;
        if(ionScroll && ionScroll.scrollToTop && this.$util.isFunction(ionScroll.scrollToTop)){
            ionScroll.scrollToTop(500);
        }
    }

    /**
     * 是否应该显示返回顶部按钮
     *
     * @memberof Shop_examineMobWFDynaExpMDViewBase
     */
    public isShouleBackTop = false;

    /**
     * 当前滚动条是否是停止状态
     *
     * @memberof Shop_examineMobWFDynaExpMDViewBase
     */
    public isScrollStop = true;


    /**
     * 当前选中tab
     *
     * @type {string}
     * @memberof Shop_examineMobWFDynaExpMDViewBase
     */
    public selectTabId: string= "";

    /**
     * tab切换
     *
     * @memberof Shop_examineMobWFDynaExpMDViewBase
     */
    public tab_click(item: any) {
        this.curSelectedNode = item;
        Object.assign(this.viewparams,
            {
                'userTaskId': item['userTaskId'],
                'processDefinitionKey': item['processDefinitionKey'],
            }
        );
        (this.$refs.mdctrl as any).load(this.viewparams);
        this.selectTabId = item.userTaskId;
    }

    /**
     * 树导航栏数据
     *
     * @type {any}
     * @memberof Shop_examineMobWFDynaExpMDViewBase
     */
    public wfStepModel: Array<any> = [];

    /**
     * 是否展开搜索表单
     *
     * @type {any}
     * @memberof  Shop_examineMobWFDynaExpMDViewBase
     */
    public isExpandSearchForm: boolean = true;

    /**
     * 是否单选
     *
     * @type {any}
     * @memberof  Shop_examineMobWFDynaExpMDViewBase
     */
    public isSingleSelect: boolean = true;

    /**
     * 左侧树的默认配置
     *
     * @type {any}
     * @memberof  Shop_examineMobWFDynaExpMDViewBase
     */
    public defaultProps: any = {
        children: 'children',
        label: 'userTaskName',
    };

    /**
     * 左侧树当前选中节点
     *
     * @type {any}
     * @memberof  Shop_examineMobWFDynaExpMDViewBase
     */
    public curSelectedNode: any;

    /**
     * 获取树导航栏数据
     *
     * @returns {Promise<any>}
     * @memberof Shop_examineMobWFDynaExpMDViewBase
     */
    public async getWFStepModel(): Promise<any> {
        this.$apploading.show();
        const response: any = await this.appEntityService.WFGetWFStep();
        this.$apploading.hidden();
        if (response && response.status === 200) {
            this.wfStepModel = response.data;
            if (this.wfStepModel && this.wfStepModel.length > 0) {
                this.curSelectedNode = this.wfStepModel[0];
                this.selectTabId = this.wfStepModel[0]['userTaskId'];
            }
            Object.assign(this.viewparams,
                {
                    'userTaskId': this.curSelectedNode['userTaskId'],
                    'processDefinitionKey': this.curSelectedNode['processDefinitionKey'],
                }
            );
        } else {
            const { error: _data } = response;
            this.$notice.error(_data.message);
        }
        return response;
    }

    /**
     * 快速搜索值
     *
     * @memberof Shop_examineMobWFDynaExpMDView
     */
    public quickValue = "";

    /**
     * 快速搜索
     *
     * @memberof Shop_examineMobWFDynaExpMDView
     */
    public async quickValueChange(event: any) {
        const mdctrl: any = this.$refs.mdctrl;
        if (mdctrl) {
            mdctrl.quickSearch(this.quickValue);
        }
    }

}
</script>

<style lang='less'>
@import './shop-examine-mob-wfdyna-exp-mdview.less';
</style>